#include "UdpListener.h"
#include"scan.h"

UdpListener::UdpListener(QObject *parent) : QObject(parent), udpSocket(new QUdpSocket(this))
{
    // 绑定到指定的端口
    if (!udpSocket->bind(QHostAddress::Any, UDPPort))
    {
        QDEBUG_FILE_FUNC << "Failed to bind UDP socket to port" << UDPPort;
    }
    else
    {
        QDEBUG_FILE_FUNC << "UDP socket bound to port " << UDPPort;
    }

    // 连接readyRead信号到槽函数
    connect(udpSocket, &QUdpSocket::readyRead, this, &UdpListener::readPendingDatagrams);
}

void UdpListener::readPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        // 读取数据报
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        // 处理接收到的数据
        QDEBUG_FILE_FUNC << "Received datagram from" << sender.toString() << ":" << senderPort;
        QDEBUG_FILE_FUNC << "Datagram content:" << QString::fromUtf8(datagram);

        Scan scan =  Scan::deCodeFromJson(datagram);
        
        QDEBUG_FILE_FUNC<<scan.hostName;
    }
}
